<!--
 * @Author: 冯本桥
 * @Date: 2025-02-13 13:54:59
 * @LastEditTime: 2025-03-04 17:29:59
 * @LastEditors: 冯本桥
 * @Description:绩效评估
 * @FilePath: \teach_system_fe\src\views\teacherManagement\performanceEvaluation.vue
-->
<template>
  <div v-loading="loading">
    <div class="header-search cad-box">
      <el-select
        v-model="searchValue.year"
        style="margin-right: 20px"
        clearable
        placeholder="请选择考核年度"
      >
        <el-option
          v-for="(item, index) in years"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
      <el-input
        v-model="searchValue.staffName"
        style="width: 15%"
        clearable
        placeholder="请输入考核对象名称"
      />

      <el-button
        style="margin-left: 20px"
        type="primary"
        @click="onSubmit"
      >确定</el-button>
    </div>

    <div class="content-table cad-box">
      <div style="margin-bottom: 20px">
        <el-button type="primary" @click="add">新增考核</el-button>
        <el-button type="primary" @click="derive">导出</el-button>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%; margin: 30px 0"
        :header-cell-style="{
          backgroundColor: '#fafafc',
          color: '#000000',
        }"
      >
        <el-table-column prop="staffName" label="考核对象" align="center" />
        <el-table-column
          v-for="(item, index) in yearsList"
          :key="index"
          :prop="item"
          :label="`${index + 1}月`"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            <el-link
              style="color: #ff8b00"
              :underline="false"
              @click="info(scope.row, index + 1)"
            >{{ scope.row[item] }}</el-link>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color: #006be7"
              size="small"
              @click="examine(scope.row)"
            >
              考核
            </el-button>
            <el-button
              style="color: #ff5757"
              type="text"
              size="small"
              @click="deleteDate(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-sizes="[10, 15, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-drawer
      :title="`${drawerTitle}`"
      :visible.sync="drawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      :wrapper-closable="false"
    >
      <div style="padding: 0 20px">
        <from-page
          ref="subFromRef"
          :rules="config.addRreRulesDate"
          :label-width="null"
          :from-config="drawerFromDate"
          :disabled-from="disabledFrom"
          :but-show="butShow"
          @submitForm="submitForm"
        >
          <template>
            <el-form-item label="最终得分" prop="finalScore">
              <el-input v-model="slotFrom.finalScore" :disabled="true" />
            </el-form-item>
            <el-form-item label="评语" prop="comment">
              <el-input
                v-model="slotFrom.comment"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 4 }"
                placeholder="若无可不填写"
              />
            </el-form-item>
          </template>
        </from-page>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapGetters } from 'vuex'
import * as config from './config'
import FromPage from '@/components/Basic/FromPage/index'

import {
  getPerformanceList,
  addPerformanceList,
  submitTeacher,
  deletePerformanceList,
  infoPerformanceList,
  exportPerformanceList
} from './api/performanceEvaluation'
export default {
  components: {
    FromPage
  },
  data () {
    return {
      config: config,
      searchValue: {
        year: dayjs(new Date()).format('YYYY'),
        month: '',
        staffName: ''
      },
      slotFrom: {
        finalScore: 0,
        comment: ''
      },
      disabledFrom: false,
      yearsList: [
        'january',
        'february',
        'march',
        'april',
        'may',
        'june',
        'july',
        'august',
        'september',
        'october',
        'november',
        'december'
      ],
      loading: false,
      years: (() => {
        const startYear = 2022
        const endYear = 2028
        const years = []
        for (let i = startYear; i <= endYear; i++) {
          years.push(i)
        }
        return years
      })(),
      drawerTitle: '',
      drawer: false,
      tableData: [],

      drawerFromDate: [
        {
          type: 'select',
          label: '考核对象',
          value: 'staffId',
          option: [],
          placeholder: '请选择考核对象'
        },
        {
          type: 'select',
          label: '考核月份',
          value: 'month',
          option: (() => {
            const startYear = 1
            const endYear = 12
            const years = []
            for (let i = startYear; i <= endYear; i++) {
              years.push({ label: `${i}月`, id: i })
            }
            return years
          })(),
          placeholder: '请选择考核月份'
        },
        {
          type: 'input',
          label: '教学能力',
          value: 'teachingAbility',
          placeholder: '请输入得分',
          changes: (value) => {
            this.slotFrom.finalScore += value * 1
          }
        },
        {
          type: 'input',
          label: '工作态度',
          value: 'workingAttitude',
          placeholder: '请输入得分',
          changes: (value) => {
            this.slotFrom.finalScore += value * 1
          }
        },
        {
          type: 'input',
          label: '专业素养',
          value: 'professional',
          placeholder: '请输入得分',
          changes: (value) => {
            this.slotFrom.finalScore += value * 1
          }
        },
        {
          type: 'rate',
          label: '家长满意度',
          value: 'parentalSatisfaction'
        },
        {
          type: 'input',
          label: '其他',
          value: 'other',
          placeholder: '请输入得分',
          changes: (value) => {
            this.slotFrom.finalScore += value * 1
          }
        }
      ],
      pagination: {
        pageNum: 0,
        pageSize: 10
      },
      total: 0,
      butShow: true
    }
  },
  computed: {
    ...mapGetters(['curArea'])
  },
  created () {
    this.getTableList()
    this.getTeacher()
  },
  mounted () {},
  methods: {
    async getTableList () {
      this.loading = true
      try {
        const siz = JSON.parse(JSON.stringify(this.pagination.pageNum))
        const res = await getPerformanceList({
          ...this.pagination,
          ...this.searchValue,
          pageNum: siz ? siz - 1 : siz
        })
        this.tableData = res.content
        this.total = res.totalElements
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    onSubmit () {
      console.log('确认')
      this.getTableList()
    },

    add () {
      console.log('新增考核')
      this.drawerTitle = '新增考核'
      this.drawer = true
      this.butShow = true
    },

    async exportDateList () {
      this.loading = true
      try {
        const res = await exportPerformanceList({
          year: this.searchValue.year
        })
        // 创建一个a标签用于下载文件
        const link = document.createElement('a')
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel'
        })
        const url = window.URL.createObjectURL(blob)
        link.href = url
        link.setAttribute('download', '教师绩效评估表.xlsx') // 设置下载文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url) // 释放URL对象
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    info (value, key) {
      console.log(value)
      this.drawerTitle = '详情'
      this.disabledFrom = true
      this.butShow = false
      this.drawer = true
      this.infoDate(value, key)
    },

    async addTableList (value) {
      try {
        await addPerformanceList({
          ...value,
          year: dayjs(new Date()).format('YYYY'),
          ...this.slotFrom
        })
        this.$message({
          type: 'success',
          message: '成功!'
        })
        this.beforeClose()
        this.getTableList()
      } catch (error) {
        console.log(error)
      }
    },

    async getTeacher () {
      const res = await submitTeacher({
        areaId: this.curArea.areaId,
        deleted: false,
        pageNum: 0,
        pageSize: 9999
      })
      this.drawerFromDate[0].option = res.content
    },

    async deleteList (id) {
      try {
        await deletePerformanceList({ id: id })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getTableList()
      } catch (error) {
        console.log(error)
      }
    },

    derive () {
      console.log('导出')
      this.exportDateList()
    },

    examine (value) {
      console.log('考核')
      this.drawerTitle = '考核'
      this.butShow = true
      this.drawer = true
      const a = JSON.parse(JSON.stringify(value))
      this.$nextTick(() => {
        this.$refs.subFromRef.formDate = a
        this.$refs.subFromRef.formDate = {}
        this.$refs.subFromRef.formDate.staffId = a.staffId
        this.$refs.subFromRef.formDate.year = dayjs(new Date()).format('YYYY')
      })
    },

    deleteDate (id) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteList(id)
        })
        .catch(() => {})
    },

    async infoDate (value, key) {
      try {
        const res = await infoPerformanceList({
          month: key,
          year: value.year,
          staffId: value.staffId
        })
        this.$nextTick(() => {
          this.$refs.subFromRef.formDate = res
          this.slotFrom = res
        })
      } catch (error) {
        console.log(error)
      }
    },

    beforeClose () {
      this.$refs.subFromRef.resetFields()
      this.disabledFrom = false
      this.slotFrom = {
        finalScore: 0,
        comment: ''
      }
      this.drawer = false
    },

    submitForm (formName) {
      if (formName !== '') {
        this.addTableList(formName)
      }
    },

    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagination.pageSize = val
      this.getTableList()
    },

    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagination.pageNum = val
      this.getTableList()
    }
  }
}
</script>

<style scoped lang="scss">
.header-search {
  display: flex;
  margin-bottom: 30px;

  .select-box {
    margin: 0 20px;
  }
}
</style>
